#!/usr/bin/env python3

# Copyright (c) 2005-2014 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


import os
from bidict import bidict


class RunningEnvironmentError(Exception):
    pass


class ConfigError(Exception):
    pass


class SyncError(Exception):
    pass


class CacheError(Exception):
    pass


class DataError(Exception):
    pass


class Handy:

    SYSTEM_DIR = "/var/cache/elemlib"

    USER_DIR = os.path.expanduser("~/.cache/elemlib")

    @staticmethod
    def compareVerion(ver1, ver2):
        # eg: 3.9.11-r1
        #     3.10.7

        partList1 = ver1.split("-")
        partList2 = ver2.split("-")

        verList1 = [int(x) for x in partList1[0].split(".")]
        verList2 = [int(x) for x in partList2[0].split(".")]
        assert len(verList1) <= 3 and all([0 <= x <= 99 for x in verList1])
        assert len(verList2) <= 3 and all([0 <= x <= 99 for x in verList2])

        verList1 += [0] * (3 - len(verList1))
        verList2 += [0] * (3 - len(verList2))

        ver1 = verList1[0] * 10000 + verList1[1] * 100 + verList1[2]
        ver2 = verList2[0] * 10000 + verList2[1] * 100 + verList2[2]
        if ver1 > ver2:
            return 1
        elif ver1 < ver2:
            return -1

        if len(partList1) >= 2 and len(partList2) == 1:
            return 1
        elif len(partList1) == 1 and len(partList2) >= 2:
            return -1

        p1 = "-".join(partList1[1:])
        p2 = "-".join(partList2[1:])
        if p1 > p2:
            return 1
        elif p1 < p2:
            return -1

        return 0

    @staticmethod
    def dataSrcFilterByType(dataSrcDict, etype):
        return [x for x in dataSrcDict.values() if etype in x.supported_etypes]

    @staticmethod
    def dataSrcGetSortedList(dataSrcDict, etype):
        return sorted(dataSrcDict.values(), key=lambda x: x.get_priority(etype), reverse=True)

    @staticmethod
    def elemGetMaxPriorityElementId(dataSrcDict, etype, esource, eindex):
        # get elementId in data source that has the highest priority
        # by iteratively invoking DataSource.map_element_reverse()

        while True:
            newSource = None
            newIndex = None
            for esource2, eindex2 in dataSrcDict[esource].map_element_reverse(etype, eindex):
                assert dataSrcDict[esource2].get_priority(etype) > dataSrcDict[esource].get_priority(etype)
                if newSource is None or dataSrcDict[esource2].get_priority(etype) > dataSrcDict[newSource].get_priority(etype):
                    newSource = esource2
                    newIndex = eindex2

            if newSource is not None:
                esource = newSource
                eindex = newIndex
                continue

            return (esource, eindex)

    @staticmethod
    def elemGetAllElementIdList(dataSrcDict, etype, esource, eindex):
        ret = [(esource, eindex)]
        oriLen = 0
        while len(ret) > oriLen:
            esource, eindex = ret[oriLen]
            for dataSrc in dataSrcDict.values():
                if dataSrc.name != esource:
                    eindex2 = dataSrc.map_element(etype, esource, eindex)
                    if eindex2 is not None:
                        assert dataSrc.get_priority(etype) < dataSrcDict[esource].get_priority(etype)
                        if (dataSrc.name, eindex2) not in ret:
                            ret.append((dataSrc.name, eindex2))
            oriLen += 1
        return ret          # FIXME: the returned list should be in order


class ElementMapType1:

    def __init__(self, data):
        self._data = data

    def map_element(self, esource, eindex):
        ret = self._data.get(esource, {}).get(eindex, None)
        return ret[0] if ret is not None else None

    def map_element_reverse(self, eindex):
        ret = []
        for k, v in self._data.items():
            for k2, v2 in v.items():
                if eindex in v2:
                    ret.append((k, k2))
        return ret


class ElementMapType2:

    def __init__(self, data):
        self._data = bidict(data)

    def map_element(self, esource, eindex):
        ret = self._data.get(esource, {}).get(eindex, None)
        return ret if ret is not None else None

    def map_element_reverse(self, eindex):
        ret = self._data.reverse.get(eindex, None)
        if ret is not None:
            return [ret]
        else:
            return []
